package decision_tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import decision_tree.dto.Sample;
import decision_tree.pos.POSManager;


public class UnigramModel implements ProbabilityModel{
	private Map<String, Double> model;
	private List<Double> ordered;

	public void train(List<Sample> sampleList) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		for (Sample sample : sampleList) {
			if (!map.containsKey(sample.getY())) {
				map.put(sample.getY(), 0);
			}
			map.put(sample.getY(), map.get(sample.getY()) + 1);
		}

		model = new HashMap<String, Double>();
		for (Entry<String, Integer> entry : map.entrySet()) {
			double prob = entry.getValue() / (double) sampleList.size();
			model.put(entry.getKey(), prob);

		}
	}
	
	@Override
	public double get(Sample key) {
		return get(key.getY());
	}
	
	protected double get(String next) {
		if(model.containsKey(next)) {
			return model.get(next);
		} else {
			return 0;
		}
	}
	
	@Override
	public String toString() {
		return model.toString();
	}
	
	public String toLine() {
		StringBuilder sb = new StringBuilder();
		for(Entry<String, Double> entry : model.entrySet()) {
			sb.append(entry.getKey());
			sb.append(":");
			sb.append(entry.getValue());
			sb.append(" ");
		}
		String result = sb.toString();
		result = result.trim().replace(" ", ";");
		return result;
	}
	
	public static UnigramModel parse(String line) {
		String [] pairs = line.split(";");
		Map<String, Double> model = new HashMap<String, Double>();
		for(String pair : pairs) {
			String [] terms = pair.split(":");
			String type = terms[0];
			double value = Double.parseDouble(terms[1]);
			model.put(type, value);
		}
		UnigramModel unigram = new UnigramModel();
		unigram.model = model;
		return unigram;
	}

	@Override
	public List<Double> getDistribution(Sample redandent) {
		if(ordered == null) {
			List<String> vocabulary = POSManager.getInstance().getVocabulary();
			ordered = new ArrayList<Double>(vocabulary.size());
			for(String key : vocabulary) {
				ordered.add(get(key));
			}
		}
		return ordered;
	}
}
